package org.znxs.comfriend.activities;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import org.znxs.comfriend.R;
import org.znxs.comfriend.adapters.ImagePreviewAdapter;
import org.znxs.comfriend.models.User;
import org.znxs.comfriend.utils.FollowManager;

public class FriendDetailActivity extends AppCompatActivity {
    private TextView tvUsername;
    private TextView tvBio;
    private TextView tvGender; // 性别 TextView
    private RecyclerView recyclerViewImages;
    private Button btnFollow; // 关注按钮
    private Button btnStartMessage; // 发送消息按钮

    private FollowManager followStance = FollowManager.getInstance(this);

    private User user; // 用户对象

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_detail);

        // 初始化控件
        initView();

        // 获取传递的 User 对象
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("user")) {
            user = (User) intent.getSerializableExtra("user");
            // 加载用户数据
            loadUserData(user);
            // 设置关注按钮的初始状态
            updateFollowButtonState();
        } else {
            Toast.makeText(this, R.string.error_no_user_data, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        tvUsername = findViewById(R.id.tv_username);
        tvBio = findViewById(R.id.tv_bio);
        tvGender = findViewById(R.id.tv_gender); // 初始化性别 TextView
        recyclerViewImages = findViewById(R.id.recycler_view_images);
        btnFollow = findViewById(R.id.btn_follow); // 初始化关注按钮
        btnStartMessage = findViewById(R.id.btn_start_message); // 初始化发送消息按钮

        // 设置 RecyclerView 的布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recyclerViewImages.setLayoutManager(layoutManager);

        // 添加 PagerSnapHelper 实现滑动固定效果
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(recyclerViewImages);

        // 设置关注按钮的点击事件
        btnFollow.setOnClickListener(v -> {
            String userId = user.getId();

            if (followStance.isFollowing(userId)) {
                // 如果已关注，则取消关注
                followStance.removeItem(userId);
                Toast.makeText(this, "已取消关注", Toast.LENGTH_SHORT).show();
            } else {
                // 如果未关注，则关注
                followStance.addItem(userId);
                Toast.makeText(this, "已关注", Toast.LENGTH_SHORT).show();
            }

            // 更新按钮状态
            updateFollowButtonState();
        });

        // 设置发送消息按钮的点击事件
        btnStartMessage.setOnClickListener(v -> {
            // 只有关注之后才能发消息
            if (followStance.isFollowing(user.getId())) {
                // 处理发送消息逻辑
                startMessagingActivity(user.getId(), user.getNickname(), user.getAvatarUrl());
            } else {
                Toast.makeText(this, "没有添加好友，请关注之后再发消息吧", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 启动聊天界面
     */
    private void startMessagingActivity(String userId, String userName, String userAvatarUrl) {
        Intent intent = new Intent(FriendDetailActivity.this, ChatActivity.class);
        intent.putExtra("receiverUserId", userId);
        intent.putExtra("receiverUserName", userName);
        intent.putExtra("receiverUserAvatarUrl", userAvatarUrl);
        startActivity(intent);
    }

    /**
     * 加载用户数据
     */
    private void loadUserData(User user) {
        if (user != null) {
            // 设置用户信息
            tvUsername.setText(user.getNickname());
            tvBio.setText(user.getBio());

            // 加载头像
            ImageView ivAvatar = findViewById(R.id.iv_avatar);
            Glide.with(this).load(user.getAvatarUrl()).placeholder(R.drawable.pengyiyan).error(R.drawable.error).into(ivAvatar);

            // 设置性别
            String genderLabel = "";
            switch (user.getGender()) { // 假设 getGender() 返回 "male" 或 "female"
                case "male":
                    genderLabel = getString(R.string.male);
                    break;
                case "female":
                    genderLabel = getString(R.string.female);
                    break;
                default:
                    genderLabel = getString(R.string.male);
                    break;
            }
            tvGender.setText(genderLabel);

            // 设置图片预览的 Adapter
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int screenWidth = displayMetrics.widthPixels;

            ImagePreviewAdapter adapter = new ImagePreviewAdapter(this, user.getImages(), screenWidth);
            recyclerViewImages.setAdapter(adapter);
        } else {
            Toast.makeText(this, R.string.error_load_user_data, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 更新关注按钮的状态
     */
    private void updateFollowButtonState() {
        String userId = user.getId();
        if (followStance.isFollowing(userId)) {
            btnFollow.setText(R.string.following);
            btnFollow.setTextColor(getColor(android.R.color.darker_gray)); // 白色文字
            btnFollow.setBackgroundColor(getColor(R.color.Following));
        } else {
            btnFollow.setText(R.string.follow);
            btnFollow.setTextColor(getColor(android.R.color.black)); // 黑色文字
            btnFollow.setBackgroundColor(getColor(R.color.Follow));
        }
    }

}